package br.indt.framework.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import br.indt.framework.log.MicrologWrapper;

import net.sf.jazzlib.GZIPInputStream;

public class ZipUtils {

	private static final MicrologWrapper log = MicrologWrapper.getLogger(ZipUtils.class);
	
	/**
	 * Decompresses the array of byte.
	 * 
	 * example: String unzippedContent = ZipUtils.unzipText(zippedContent);
	 * 
	 * @param 	zippedText	Array of the byte compressed.
	 * @return	String decompressed.
	 */
	public static String unzipText(byte[] zippedText) {
		
		String outputString = StringUtils.EMPTY;
		InputStream is = null;
		GZIPInputStream gzip = null;
		ByteArrayOutputStream os = null;

		try {
			os = new ByteArrayOutputStream();
			is = new ByteArrayInputStream(zippedText); 
			gzip = new GZIPInputStream(is);

			byte[] buffer = new byte[1024];
			
			int c = 0;
			while ((c = gzip.read(buffer,0,1024)) != -1) {
				os.write(buffer,0,c);
			}

			byte[] output = os.toByteArray();

			// decode the bytes into a string
			
			outputString = new String(output, 0, output.length, "UTF-8");
			
		} catch (Exception e) {
			log.error("unzipText - " + e.getMessage());
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (Exception e) {					
				}
			}
			
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
			
			if (gzip != null) {
				try {
					gzip.close();
				} catch (Exception e) {
				}
			}
		}

		return outputString;
	}
}